#include "levelbeginstate.h"
#include "levelstate.h"

LevelBeginState::LevelBeginState(GameEngine* engine) : GameState(engine)
{
	m_server = nullptr;
	m_client = nullptr;
	m_level = nullptr;

	m_shutdown_network_on_state_end = true;
	m_ready_signal_sent = false;
}

LevelBeginState::~LevelBeginState()
{
	if (m_is_server)
		ServerCleanup();
	else
		ClientCleanup();

	if (m_shutdown_network_on_state_end)
	{
		delete m_level;
	}

	al_destroy_timer(m_fade_in_timer);
	al_destroy_timer(m_fade_out_timer);

	al_destroy_font(m_standard_font);
}

void LevelBeginState::Init(bool is_server, RakNetServer* server, RakNetClient* client,
								ClientConnectionList client_list, Level* level)
{
	// Take the information from the previous state. Server and/or client might be nullpointers.
	m_is_server = is_server;
	m_server = server;
	m_client = client;
	m_client_list = client_list;

	m_level = level;

	m_fade_in_timer = al_create_timer(0.01f);
	m_fade_out_timer = al_create_timer(0.01f);
	al_start_timer(m_fade_in_timer);

	m_standard_font = al_load_font(STANDARD_FONT.c_str(), STANDARD_FONT_SIZE, NULL);

	if (m_is_server)
		ServerInit();
	else
		ClientInit();
}

void LevelBeginState::HandleInput(ALLEGRO_EVENT next_event)
{
	// Only do something if the fade in is complete.
	if (!al_get_timer_started(m_fade_in_timer) &&
		(next_event.type == ALLEGRO_EVENT_KEY_DOWN || next_event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN))
	{
		al_start_timer(m_fade_out_timer);
	}
}

void LevelBeginState::Update(float timing_factor)
{
	if (m_is_server)
		ServerUpdate();
	if (m_client)
		ClientUpdate();

	if (al_get_timer_count(m_fade_in_timer) > 100)
		al_stop_timer(m_fade_in_timer);
}

void LevelBeginState::Draw()
{
	// Usually the fad e is 100% transparent i.e. no fade.
	float fade_transparency = 1.0f;
	if (al_get_timer_started(m_fade_in_timer))
		fade_transparency = al_get_timer_count(m_fade_in_timer)/100.0f;
	if (al_get_timer_started(m_fade_out_timer))
		fade_transparency = 1.0f - al_get_timer_count(m_fade_out_timer)/100.0f;
	RangeContraint(fade_transparency);

	al_draw_text(m_standard_font, al_map_rgb(255,255,255), 512, 10, ALLEGRO_ALIGN_CENTER, m_level->title.c_str());
	al_draw_bitmap(m_level->graphics(), 10, 10, NULL);

	al_draw_textf(m_standard_font, al_map_rgb(255,255,255), 10, 400, NULL, "Number of Lems: %d", m_level->number_of_lems);
	al_draw_textf(m_standard_font, al_map_rgb(255,255,255), 10, 420, NULL, "Number to save: %d (%d%%)", m_level->lems_to_save,
		(m_level->lems_to_save * 100) / m_level->number_of_lems);

	// Draw the fade.
	al_draw_filled_rectangle(0, 0, 1023, 767, al_map_rgba_f(0.0f, 0.0f, 0.0f, 1.0f - fade_transparency));
}